﻿using ICSharpCode.AvalonEdit;
using MahApps.Metro.Controls.Dialogs;
using Newtonsoft.Json;
using PDFDesign.Command;
using PDFDesign.Common;
using PDFDesign.Model;
using PDFDesign.Properties;
using PDFDesign.Repository;
using PDFDesign.Window;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Linq;
using System.Windows.Input;

namespace PDFDesign.ViewModel
{
    public class MainViewModel : BaseViewModel
    {
        private TextEditor textEditor;

        public MainViewModel(TextEditor textEditor)
        {
            this.textEditor = textEditor;
            RefreshCommand.Execute(null);
            nodeList.Add(new NodeModel { Name = "123", Children = new List<NodeModel> { new NodeModel { Name = "456" }, new NodeModel { Name = "789" } } });
        }

        private string searchTemplateName;
        /// <summary>
        /// 查询模板名
        /// </summary>
        public string SearchTemplateName
        {
            get => searchTemplateName;
            set
            {
                searchTemplateName = value;
                OnPropertyChanged("SearchTemplateName");
            }
        }

        private int currentIndex;
        /// <summary>
        /// 当前页面索引
        /// </summary>
        public int CurrentIndex
        {
            get => currentIndex;
            set
            {
                currentIndex = value;
                OnPropertyChanged("CurrentIndex");
            }
        }

        private bool isDesgin;
        /// <summary>
        /// 是否为设计界面
        /// </summary>
        public bool IsDesgin
        {
            get => isDesgin;
            set
            {
                if (isDesgin)
                {
                    currentStyle.PDFStyle.Controls.Texts = TextList.ToList();
                    currentStyle.PDFStyle.Controls.Tables[0].Rows = RowList.ToList();
                    StyleContent = JsonConvert.SerializeObject(currentStyle.PDFStyle, Formatting.Indented);
                }
                else
                {
                    if (CheckStyleJson(out PDFStyle style))
                    {
                        TextList = new ObservableCollection<TextControl>(style.Controls.Texts);
                        RowList = new ObservableCollection<RowControl>(style.Controls.Tables[0].Rows);
                    }
                    else
                    {
                        ShowMessage("请检查json格式是否正确");
                        return;
                    }
                }
                isDesgin = value;
                CurrentIndex = isDesgin ? 1 : 0;
                OnPropertyChanged("IsDesgin");
            }
        }

        private ObservableCollection<ReportStyleViewModel> reportStyles = new ObservableCollection<ReportStyleViewModel>();
        /// <summary>
        /// 样式列表
        /// </summary>
        public ObservableCollection<ReportStyleViewModel> ReportStyles
        {
            get => reportStyles;
            set
            {
                reportStyles = value;
                OnPropertyChanged("ReportStyles");
            }
        }

        private ReportStyleViewModel selectStyle;
        /// <summary>
        /// 选择样式
        /// </summary>
        public ReportStyleViewModel SelectStyle
        {
            get => currentStyle;
            set
            {
                selectStyle = value;
                CurrentStyle = value;
                OnPropertyChanged("SelectStyle");
            }
        }

        private ReportStyleViewModel currentStyle;
        /// <summary>
        /// 当前样式
        /// </summary>
        public ReportStyleViewModel CurrentStyle
        {
            get => currentStyle;
            set
            {
                currentStyle = value;
                OnPropertyChanged("CurrentStyle");
                if (currentStyle == null) return;
                StyleContent = Utils.JsonFormat(currentStyle.ReportStyle.Content);
                TextList = new ObservableCollection<TextControl>(currentStyle.PDFStyle.Controls.Texts);
                RowList = new ObservableCollection<RowControl>(currentStyle.PDFStyle.Controls.Tables[0].Rows);
            }
        }

        private string styleContent = "";
        /// <summary>
        /// 样式信息
        /// </summary>
        public string StyleContent
        {
            get => styleContent;
            set
            {
                styleContent = value;
                textEditor.Text = styleContent;
                OnPropertyChanged("StyleContent");
            }
        }

        private ObservableCollection<TextControl> textList;
        /// <summary>
        /// 控件列表
        /// </summary>
        public ObservableCollection<TextControl> TextList
        {
            get => textList;
            set
            {
                textList = value;
                if (textList != null && textList.Count != 0)
                {
                    CurrentText = textList[0];
                }
                OnPropertyChanged("TextList");
            }
        }

        private TextControl currentText;
        /// <summary>
        /// 当前控件
        /// </summary>
        public TextControl CurrentText
        {
            get => currentText;
            set
            {
                currentText = value;
                OnPropertyChanged("CurrentText");
            }
        }

        private ObservableCollection<RowControl> rowList;
        /// <summary>
        /// 行列表
        /// </summary>
        public ObservableCollection<RowControl> RowList
        {
            get => rowList;
            set
            {
                rowList = value;
                if (rowList != null && rowList.Count != 0)
                {
                    CurrentRow = rowList[0];
                }
                OnPropertyChanged("RowList");
            }
        }

        private RowControl currentRow;
        /// <summary>
        /// 当前行
        /// </summary>
        public RowControl CurrentRow
        {
            get => currentRow;
            set
            {
                currentRow = value;
                if (currentRow != null && currentRow.Cells != null) CellList = new ObservableCollection<CellControl>(currentRow.Cells);
                OnPropertyChanged("CurrentRow");
            }
        }

        private ObservableCollection<CellControl> cellList;
        /// <summary>
        /// 单元格列表
        /// </summary>
        public ObservableCollection<CellControl> CellList
        {
            get => cellList;
            set
            {
                cellList = value;
                if (cellList != null && cellList.Count != 0)
                {
                    CurrentCell = cellList[0];
                }
                OnPropertyChanged("CellList");
            }
        }

        private CellControl currentCell;
        /// <summary>
        /// 当前单元格
        /// </summary>
        public CellControl CurrentCell
        {
            get => currentCell;
            set
            {
                currentCell = value;
                OnPropertyChanged("CurrentCell");
            }
        }

        /// <summary>
        /// 添加样式
        /// </summary>
        public ICommand AddCommand
        {
            get => new AnotherCommand(_ =>
            {

                var addStyleViewModel = new AddStyleViewModel();
                var window = new AddStyleWindow { DataContext = addStyleViewModel };
                var flag = window.ShowDialog();
                if (flag.HasValue && flag.Value)
                {
                    selectStyle = null;
                    OnPropertyChanged("SelectStyle");
                    CurrentStyle = addStyleViewModel.ReportStyleViewModel;
                }
            });
        }

        /// <summary>
        /// 移除选中行
        /// </summary>
        public ICommand RemoveSelectedItemCommand { get => new AnotherCommand(_ => RemoveSelectedItem()); }

        private async void RemoveSelectedItem()
        {
            if (SelectStyle == null)
            {
                ShowMessage("请选择需要删除的样式");
                return;
            }
            MessageDialogResult result = await DialogCoordinator.Instance.ShowMessageAsync(this, "温馨提示", $"是否确定删除({currentStyle.ReportStyle.TemplateName}-{currentStyle.ReportStyle.StyleName})?", MessageDialogStyle.AffirmativeAndNegative);
            if (result == MessageDialogResult.Negative) return;
            // 执行删除操作
            ReportStyleRepository.GetInstance().Delete(SelectStyle.ReportStyle.Id);
            RefreshCommand.Execute(null);
        }

        /// <summary>
        /// 刷新列表
        /// </summary>
        public ICommand RefreshCommand
        {
            get => new AnotherCommand(_ =>
             {
                 try
                 {
                     var reportStyles = ReportStyleRepository.GetInstance().GetReportStyleList(SearchTemplateName);
                     ReportStyles = new ObservableCollection<ReportStyleViewModel>();
                     int i = 0;
                     reportStyles.ForEach(style =>
                     {
                         try
                         {
                             ReportStyles.Add(new ReportStyleViewModel
                             {
                                 Num = ++i,
                                 ReportStyle = style,
                                 PDFStyle = JsonConvert.DeserializeObject<PDFStyle>(style.Content)
                             });
                         }
                         catch (Exception) { }
                     });
                     textEditor.Text = "";
                 }
                 catch (Exception ex)
                 {
                     throw ex;
                 }
             });
        }

        /// <summary>
        /// 提示消息
        /// </summary>
        /// <param name="message"></param>
        private void ShowMessage(string message) => DialogCoordinator.Instance.ShowMessageAsync(this, "温馨提示", message, MessageDialogStyle.Affirmative);

        /// <summary>
        /// 保存
        /// </summary>
        public ICommand SaveCommand
        {
            get => new AnotherCommand(async _ =>
            {
                var result = await DialogCoordinator.Instance.ShowMessageAsync(this, "温馨提示", "保存将修改数据库,确定修改?", MessageDialogStyle.AffirmativeAndNegative);
                if (result == MessageDialogResult.Negative) return;
                if (selectStyle == null && currentStyle == null) return;
                if (string.IsNullOrWhiteSpace(currentStyle.ReportStyle.StyleName) || string.IsNullOrWhiteSpace(currentStyle.ReportStyle.TemplateName))
                {
                    ShowMessage("模板名或样式名为空");
                    return;
                }
                if (!CheckStyleJson(out PDFStyle style))
                {
                    ShowMessage($"样式格式错误");
                    return;
                }
                currentStyle.ReportStyle.Content = JsonConvert.SerializeObject(style);
                var res = ReportStyleRepository.GetInstance();
                if (selectStyle != null)
                {
                    ShowMessage("更新" + (res.Update(currentStyle.ReportStyle) ? "成功" : "失败"));
                    return;
                }
                var id = res.Insert(currentStyle.ReportStyle);
                ShowMessage("添加" + (id != null ? "成功" : "失败"));
                RefreshCommand.Execute(null);
            });
        }

        /// <summary>
        /// 验证样式格式是否正确
        /// </summary>
        /// <returns></returns>
        private bool CheckStyleJson(out PDFStyle style)
        {
            try
            {
                if (IsDesgin)
                {
                    currentStyle.PDFStyle.Controls.Texts = TextList.ToList();
                    currentStyle.PDFStyle.Controls.Tables[0].Rows = RowList.ToList();
                    style = currentStyle.PDFStyle;
                    return true;
                }
                style = JsonConvert.DeserializeObject<PDFStyle>(textEditor.Text);
                return style != null &&
                    style.PageSetting != null &&
                    style.Controls != null &&
                    style.Controls.Texts != null &&
                    style.Controls.Tables != null &&
                    style.Controls.Tables.Count != 0;
            }
            catch
            {
                style = null;
                return false;
            }
        }

        /// <summary>
        /// 还原修改
        /// </summary>
        public ICommand ReductionCommand { get => new AnotherCommand(_ => StyleContent = Utils.JsonFormat(currentStyle.ReportStyle.Content)); }
        /// <summary>
        /// 设置数据
        /// </summary>
        public ICommand SetDataCommand
        {
            get => new AnotherCommand(_ =>
            {
                new MockDataWindow().ShowDialog();
            });
        }
        /// <summary>
        /// 预览页
        /// </summary>
        private ViewWindow viewWindow;
        /// <summary>
        /// 预览
        /// </summary>
        public ICommand PreviewCommand
        {
            get => new AnotherCommand(_ =>
             {
                 try
                 {
                     if (!CheckStyleJson(out PDFStyle style))
                     {
                         ShowMessage("样式格式错误");
                         return;
                     }
                     var json = JsonConvert.SerializeObject(style);
                     var data = Settings.Default.LastSaveData;
                     if (string.IsNullOrWhiteSpace(data))
                     {
                         ShowMessage("请先设置数据后预览");
                         return;
                     }
                     var viewViewModel = ViewViewModel.GetInstance();
                     if (viewWindow == null)
                     {
                         viewWindow = new ViewWindow
                         {
                             DataContext = viewViewModel
                         };
                         viewWindow.Closed += (sender, e) => viewWindow = null;
                         viewWindow.Show();
                     }
                     viewViewModel.UpdateUrl(json, data);
                 }
                 catch (Exception ex)
                 {
                     ShowMessage(ex.Message);
                 }
             });
        }
        /// <summary>
        /// 格式化
        /// </summary>
        public ICommand FormatCommand { get => new AnotherCommand(_ => StyleContent = Utils.JsonFormat(textEditor.Text)); }
        /// <summary>
        /// 主题设置
        /// </summary>
        public ICommand ThemeSettingCommand { get => new AnotherCommand(_ => new PaletteWindow().ShowDialog()); }
        /// <summary>
        /// 获取帮助
        /// </summary>
        public ICommand GetHelpCommand { get => new AnotherCommand(_ => Process.Start("tencent://Message/?Uin=935411557&websiteName=blog.silkage.net&Menu=yes")); }
        /// <summary>
        /// 帮助文档
        /// </summary>
        public ICommand DocumentCommand { get => new AnotherCommand(_ => Process.Start("https://www.wsgjp.com/")); }
        /// <summary>
        /// 页面设置
        /// </summary>
        public ICommand SettingCommand
        {
            get => new AnotherCommand(_ =>
            {
                if (CurrentStyle == null)
                {
                    ShowMessage("请选择或添加样式");
                    return;
                }
                var window = new AddStyleWindow(CurrentStyle);
                var flag = window.ShowDialog();
                if (flag.HasValue && flag.Value)
                {
                    var viewModel = ((AddStyleViewModel)window.DataContext).ReportStyleViewModel;
                    viewModel.ReportStyle.Content = JsonConvert.SerializeObject(viewModel.PDFStyle);
                    CurrentStyle = viewModel;
                }
            });
        }
        /// <summary>
        /// 添加控件
        /// </summary>
        public ICommand AddTextCommand
        {
            get => new AnotherCommand(_ =>
            {
                var text = new TextControl
                {
                    Caption = "新增控件",
                    Name = "新增控件",
                    Font = new Font2(),
                    Rect = new Rect()
                };
                TextList.Add(text);
                CurrentText = text;
            });
        }
        /// <summary>
        /// 删除控件
        /// </summary>
        public ICommand DelTextCommand
        {
            get => new AnotherCommand(_ =>
            {
                if (CurrentText == null)
                {
                    ShowMessage("请先选择控件");
                    return;
                }
                TextList.Remove(CurrentText);
            });
        }
        /// <summary>
        /// 清空控件
        /// </summary>
        public ICommand ClearTextCommand
        {
            get => new AnotherCommand(async _ =>
            {
                var result = await DialogCoordinator.Instance.ShowMessageAsync(this, "温馨提示", "是否确定清空?", MessageDialogStyle.AffirmativeAndNegative);
                if (result == MessageDialogResult.Negative) return;
                TextList.Clear();
            });
        }
        /// <summary>
        /// 添加行
        /// </summary>
        public ICommand AddRowCommand
        {
            get => new AnotherCommand(_ =>
            {
                var row = new RowControl
                {
                    Cells = new List<CellControl>()
                };
                RowList.Add(row);
                CurrentRow = row;
            });
        }
        /// <summary>
        /// 删除行
        /// </summary>
        public ICommand DelRowCommand
        {
            get => new AnotherCommand(_ =>
            {
                if (CurrentRow == null)
                {
                    ShowMessage("请先选择行");
                    return;
                }
                RowList.Remove(CurrentRow);
            });
        }
        /// <summary>
        /// 清空行
        /// </summary>
        public ICommand ClearRowCommand
        {
            get => new AnotherCommand(async _ =>
            {
                var result = await DialogCoordinator.Instance.ShowMessageAsync(this, "温馨提示", "是否确定清空?", MessageDialogStyle.AffirmativeAndNegative);
                if (result == MessageDialogResult.Negative) return;
                RowList.Clear();
            });
        }
        /// <summary>
        /// 添加单元格
        /// </summary>
        public ICommand AddCellCommand
        {
            get => new AnotherCommand(_ =>
            {
                var cell = new CellControl
                {
                    Name = "新增单元格",
                    Text = "新增单元格",
                    Font = new Font2()
                };
                CellList.Add(cell);
                CurrentRow.Cells = CellList.ToList();
                CurrentCell = cell;
            });
        }
        /// <summary>
        /// 删除单元格
        /// </summary>
        public ICommand DelCellCommand
        {
            get => new AnotherCommand(_ =>
            {
                if (CurrentCell == null)
                {
                    ShowMessage("请先选择单元格");
                    return;
                }
                CellList.Remove(CurrentCell);
                CurrentRow.Cells = CellList.ToList();
            });
        }
        /// <summary>
        /// 清空单元格
        /// </summary>
        public ICommand ClearCellCommand
        {
            get => new AnotherCommand(async _ =>
            {
                var result = await DialogCoordinator.Instance.ShowMessageAsync(this, "温馨提示", "是否确定清空?", MessageDialogStyle.AffirmativeAndNegative);
                if (result == MessageDialogResult.Negative) return;
                CellList.Clear();
                CurrentRow.Cells = CellList.ToList();
            });
        }

        private ObservableCollection<NodeModel> nodeList = new ObservableCollection<NodeModel>();
        public ObservableCollection<NodeModel> NodeList
        {
            get => nodeList;
            set
            {
                nodeList = value;
                OnPropertyChanged("NodeList");
            }
        }
    }
}
